package com.chen.tliaswebtest.interceptor;

import com.chen.tliaswebtest.utils.CurrentHolderUtils;
import com.chen.tliaswebtest.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author chen
 * @version 1.0
 * @create_date 2025/7/26
 * 拦截器，登录拦截，验证是否已经登录
 */
@Slf4j
@Component
public class LogInInterceptor implements HandlerInterceptor {
    // //目标资源方法执行前执行，放回true：放行，返回false：不放行
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        String token = request.getHeader("token");
        // 判断用户是否登录(token为空)
        if (token == null) {
            log.warn("用户未登录，请先登录!");
            // 用户未登录，重定向到登录页面
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }

        try {
            Claims claims = JwtUtils.parseJWT(token);
            Integer empId = Integer.valueOf(claims.get("id").toString());
            // 登录成功，将员工id保存到当前线程中
            CurrentHolderUtils.setCurrentId(empId);
        } catch (Exception e) {
            log.warn("令牌解析失败!,错误原因：{}", e.getMessage());
            // 令牌解析失败，重定向到登录页面
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        return true;
    }

    //目标资源方法执行后执行
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        //清空当前线程绑定的id
        CurrentHolderUtils.remove();
    }

    //视图渲染完毕后执行，最后执行
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {

    }
}
